import messageEl from "./index.vue"
import {createApp} from "vue"

const TYPEARR = ['success','warning','info','error']
let messageElArr = []


const moveUpMessage = (arr=[]) => {
    arr.forEach((vm,index) =>{
        vm.setTop(index + 1)
    })
}

const hideMessage = (app,vm,duration) => {
    setTimeout(() => {
        vm.setVisible(false).then(_=>{
            messageElArr = messageElArr.filter(ele => ele != vm)
            moveUpMessage(messageElArr)
            app.unmount()
        })
    }, duration || 3000);
}
const showMessage = (app,duration) => {
    const oflag = document.createDocumentFragment()
    const vm = app.mount(oflag)
    document.body.appendChild(oflag)
    
    messageElArr.push(vm)
    vm.setVisible(true)
    vm.setTop(messageElArr.length)
    hideMessage(app,vm,duration)
}

const message = (options) => {
    const app = createApp(messageEl,options)
    showMessage(app,options.duration)
}
TYPEARR.forEach(ele => {
    message[ele] = (options) => {
        options.type = ele
        return message(options)
    }   
})

export default message